/**
 * Created by dongchen on 15/12/16.
 */
var _ = require("lodash");

function valid(req, res, next){

    var app = singleton.app;

    //过滤掉不需要登录验证的url
    if(excludeUrl(req)){
        delete app.locals.user;
        next();
        return;
    }

    if(!includeUrl(req)){
        delete app.locals.user;
        next();
        return;
    }

    if(!req.session.user){
        console.log(req.path);
        console.log("用户没有登录");
        delete app.locals.user;
        if(req.xhr){
            //ajax request
            res.json({
                code : 500,
                msg  : '用户没有登录，请刷新页面登录'
            });
        }else{
            //common request
            res.redirect('/login');
        }

    }else{
        app.locals.user = req.session.user;
        next();
    }
}

function excludeUrl(req){

    var path = req.path;
    var excludeArray = [
        '/login',
        '/images',
        '/js',
        '/css',
        '/wechat',
        '/test'
    ];

    return _.indexOf(excludeArray, path) >= 0;
}

function includeUrl(req){
    var path = req.path;
    var includeArray = [
        '/admin'
    ];

    return _.indexOf(includeArray, path) >= 0;
}

module.exports = {
    valid : valid
};